package org.hybridlabs.source.formatter.internal;

import java.lang.reflect.Method;

import org.hybridlabs.source.beautifier.CharacterSequence;

public class CompatibilityHelper {

    /**
     * Resolves compatibility issue concerning FileHandle changes.
     *
     * @param info
     * @param charSequence
     * @return
     */
    public static CharSequence getBuffer(org.openarchitectureware.xpand2.output.FileHandle info) {
        try {
            Method getterMethod = info.getClass().getMethod("getBuffer", (Class[])null);
            return (CharSequence) getterMethod.invoke(info, (Object[])null);
        } catch (Exception e) {
            throw new RuntimeException("Incompatibilty with oAW classes. Method getBuffer cannot be invoked.", e);
        }
    }

    /**
     * Resolves compatibility issue concerning FileHandle changes.
     *
     * @param info
     * @param sequence
     */
    public static void setBuffer(org.openarchitectureware.xpand2.output.FileHandle info, CharacterSequence sequence) {
        try {
            try {
                // from version 4.2.0 on
                Method method = info.getClass().getMethod("setBuffer", new Class[] {CharSequence.class});
                method.invoke(info, new Object[] {sequence});
                return;
            } catch (NoSuchMethodException e) {
                // method does not exist
            }

            try {
                // until version 4.1.x
                Method method = info.getClass().getMethod("setBuffer", new Class[] {StringBuffer.class});
                method.invoke(info, new Object[] {sequence.getStringBuffer()});
                return;
            } catch (NoSuchMethodException e) {
                // method does not exist
            }

        } catch (Exception e) {
            throw new RuntimeException("Incompatibilty with oAW classes. Method setBuffer with expected parameters not found.", e);
        }
        throw new RuntimeException("Incompatibilty with oAW classes. Method setBuffer with expected parameters not found.");
    }

}
